#include "tlistview.h"
#include <QMouseEvent>
#include "common/tdebug.h"
#include <QScrollBar>
#include <QTimer>

TListView::TListView(QWidget *parent) :
    QListView(parent)
{
    mBar = this->verticalScrollBar();


    mIsLongPress = false;
    pressTime=500;
    mIsDoubleClick = false;
    isDown = false;

    mTimer=new QTimer(this);
    mTimer->setSingleShot(true);

   connect(mTimer,SIGNAL(timeout()),this,SLOT(timeOutProcess()));

}

void TListView::setBarRange(int min,int max)
{
    Q_UNUSED(min);
    Q_UNUSED(max);
}

void TListView::showEvent(QShowEvent *e)
{
    QListView::showEvent(e);

    mBar->setRange(0,(pages()-1)*mBar->pageStep());
}

void TListView::pageUp()
{
    mBar->setValue(mBar->value()-mBar->pageStep());

}

void TListView::pageDown()
{
    mBar->setValue(mBar->value()+mBar->pageStep());
}

int TListView::pages()
{
    return ((mBar->maximum()-mBar->minimum())+mBar->pageStep()-1)/(mBar->pageStep())+1;
}

int TListView::currentPage()
{
    return ((mBar->value()-mBar->minimum())+mBar->pageStep()-1)/(mBar->pageStep())+1            ;
}


bool TListView::isOnBottom()
{
    if(mBar->value()>=mBar->maximum())
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool TListView::isOnTop()
{
    if(mBar->value()<=mBar->minimum())
    {
        return true;
    }
    else
    {
        return false;
    }
}

QModelIndexList TListView::selectedIndexes() const
{
    return QListView::selectedIndexes();
}

void TListView::timeOutProcess()
{

    if(this->isDown)
    {
        emit longPress(this->currentIndex());
    }
    else if(!mIsDoubleClick)
    {
        emit singleclicked(this->currentIndex());
    }

}

void TListView::mousePressEvent(QMouseEvent *event)
{
      isDown = true;
      if(mTimer->isActive())
      {
          mIsDoubleClick =true;
          emit doubleclicked(this->currentIndex());

          mTimer->stop();
          return;
      }
      else
      {
          mTimer->start(250);
          mIsDoubleClick = false;
      }

      QListView::mousePressEvent(event);
}

void TListView::mouseReleaseEvent(QMouseEvent *event)
{
     isDown = false;
     if(mTimer->isActive())
     {
        mTimer->stop();
        mTimer->start(50);
     }

     QListView::mouseReleaseEvent(event);
}



//void TListView::setPressTime(int time)
//{
//    pressTime=time;
//}
